import type { HookFetchPlugin } from 'hook-fetch';
import { ElMessage } from 'element-plus';
import hookFetch from 'hook-fetch';
import { sseTextDecoderPlugin } from 'hook-fetch/plugins';
import router from '@/routers';
import { safeGetUserStore } from './storeUtils';

interface responseConfig {
  "url": "/sys/menu/nav",
  "baseURL": "http://192.168.1.151:8072/report-admin",
  "params": {},
  "withCredentials": false,
  "method": "GET",
  "headers": {},
  "qsArrayFormat": "repeat"
}
interface responseRes {
  code: number;
  data: never;
  msg: string;
  rows: never;
}
interface BaseResponse {
  "config": responseConfig,
  "response": {},
  "responseType": "json",
  "controller": {},
  "result": responseRes
}

export const request = hookFetch.create<BaseResponse, 'data' | 'rows'>({
  baseURL: import.meta.env.VITE_API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  plugins: [sseTextDecoderPlugin({ json: true, prefix: 'data:' })],
});

function jwtPlugin(): HookFetchPlugin<BaseResponse> {
  return {
    name: 'jwt',
    beforeRequest: async (config) => {
      const userStore = await safeGetUserStore();

      config.headers = new Headers(config.headers);
      if (userStore?.token) {
        config.headers.set('authorization', `Bearer ${userStore.token}`);
        config.headers.set('token', userStore.token);
      }
      config.data && ((config.data as any)['_t'] = new Date().getTime())
      return config;
    },
    afterResponse: async (response) => {
      console.log(response);
      if (response.result?.code === 200) {
        return response;
      }

      // 处理403逻辑
      if (response.result?.code === 403) {
        // 跳转到403页面（确保路由已配置）
        router.replace({
          name: '403',
        });
        ElMessage.error(response.result?.msg);
        return Promise.reject(response);
      }

      // 处理401逻辑
      if (response.result?.code === 401) {
        const userStore = await safeGetUserStore();
        if (userStore) {
          // 如果没有权限，退出，且弹框提示登录
          userStore.logout();
          userStore.openLoginDialog();
        }
      }

      ElMessage.error(response.result?.msg);
      return Promise.reject(response);
    },
  };
}

request.use(jwtPlugin());

export const post = request.post;

export const get = request.get;

export const put = request.put;

export const del = request.delete;

export default request;
